//
//  FGMessageConvert.m
//  FGChatKit-UI
//
//  Created by feige on 2023/5/8.
//

#import "FGMessageConvert.h"

#import <FGChatUI/FGTextMessageCellData.h>
#import <FGChatUI/FGImageMessageCellData.h>
#import <FGChatUI/FGFileMessageCellData.h>
#import <FGChatUI/FGSystemMessageCellData.h>
#import <FGChatUI/FGTemplateMessageCellData.h>

#import <MJExtension/MJExtension.h>

@implementation FGMessageConvert

#pragma mark - Private Method

/**
 * 格式化文件大小
 */
+ (NSString *)fg_formatLength:(long)length
{
    double len = length;
    NSArray *array = [NSArray arrayWithObjects:@"Bytes", @"K", @"M", @"G", @"T", nil];
    int factor = 0;
    while (len > 1024) {
        len /= 1024;
        factor++;
        if(factor >= 4){
            break;
        }
    }
    return [NSString stringWithFormat:@"%4.2f%@", len, array[factor]];
}

#pragma mark - Public Method

/**
 * 消息转cellData
 */
+ (FGMessageCellData *)cellDataForMessage:(FGChatMessageModel *)model
{
    FGMsgDirection direction = model.isSelfSend ? FGMsgDirectionOutgoing : FGMsgDirectionIncoming;
    NSString *time = model.time;
    NSString *name = model.nickname;

    if ([[model.from componentsSeparatedByString:@"/"].lastObject isEqualToString:name] && [model.status isEqualToString:@"visitor"]) {
        name = @"访客";
    }
    
    FGMessageCellData *data = nil;
    
    // 文字
    if (model.msgType == FGChatMessageTypeCommon) {
        data = [[FGTextMessageCellData alloc] initWithDirection:direction];
        ((FGTextMessageCellData *)data).content = model.content;
        ((FGTextMessageCellData *)data).textColor = model.isSelfSend ? [UIColor whiteColor] : [UIColor blackColor];
    }
    // 图片
    else if (model.msgType == FGChatMessageTypeImage) {
        data = [[FGImageMessageCellData alloc] initWithDirection:direction];
        FGImageItem *item = [[FGImageItem alloc] init];
        item.url = model.content;
        if (model.imageWidth > 0) {
            item.size = CGSizeMake(model.imageWidth, model.imageHeight);
        } else {
            item.size = CGSizeMake(800, 600);
        }
        ((FGImageMessageCellData *)data).items = @[item].mutableCopy;
    }
    // 文件
    else if (model.msgType == FGChatMessageTypeFile) {
        data = [[FGFileMessageCellData alloc] initWithDirection:direction];
        ((FGFileMessageCellData *)data).fileName = model.fileName;
        ((FGFileMessageCellData *)data).length = model.fileSize.intValue;
        ((FGFileMessageCellData *)data).url = model.content;
    }
    // 模板
    else if (model.msgType == FGChatMessageTypeTemplate) {
        data = [[FGTemplateMessageCellData alloc] initWithDirection:direction];
        ((FGTemplateMessageCellData *)data).templateData = [model.tempJson mj_JSONObject];
    }
    // 系统
    else {
        data = [[FGSystemMessageCellData alloc] initWithDirection:direction];
        ((FGSystemMessageCellData *)data).content = model.content;
    }
    
    // 通用设置
    data.uuid = model.mid;
    data.msgId = model.mid;
    data.showName = YES;
    data.conversationId = model.room;
    data.time = time;
    data.name = name;
    data.sender = model.ofrom;
    data.status = model.sendStatus;
    data.avatarUrl = model.headImg;
    data.isread = model.isRead ? @"已读" : @"未读";
    if (!model.status || model.status.length == 0) {
        data.isread = @"";
    }
    
    return data;
}

/**
 * cellData转消息
 */
+ (FGChatMessageModel *)messageForCellData:(FGMessageCellData *)cellData
                                      room:(NSString *)room
                                 websiteId:(NSNumber *)websiteId
{
    FGChatMessageModel *model = [FGChatMessageModel new];
    model.status = @"visitor";
    model.type = @"groupchat";
    model.isSelfSend = YES;
    model.websiteId = websiteId;
    model.ofrom = [FGChatKit sharedKit].chatSelfId;
    model.companyId = [FGChatKit sharedKit].companyId;
    
    model.to = room;
    model.room = room;
    // cellData
    model.mid = cellData.uuid;
    model.time = cellData.time;
    model.sendStatus = cellData.status;
    
    // 文字
    if ([cellData isKindOfClass:FGTextMessageCellData.class]) {
        model.msgType = FGChatMessageTypeCommon;
        model.notice = ((FGTextMessageCellData *)cellData).content;
        model.content = ((FGTextMessageCellData *)cellData).content;
    }
    // 图片
    else if ([cellData isKindOfClass:FGImageMessageCellData.class]) {
        model.msgType = FGChatMessageTypeImage;
        model.notice = @"[图片]";
        FGImageItem *item = ((FGImageMessageCellData *)cellData).items.lastObject;
        model.content = item.url;
        model.imageWidth = item.size.width;
        model.imageHeight = item.size.height;
    }
    // 文件
    else if ([cellData isKindOfClass:FGFileMessageCellData.class]) {
        FGFileMessageCellData *tempData = (FGFileMessageCellData *)cellData;
        model.msgType = FGChatMessageTypeFile;
        model.notice = @"[文件]";
        model.content = tempData.url;
        model.fileName = tempData.fileName;
        model.fileType = [tempData.fileName pathExtension];
        model.fileSize = [FGMessageConvert fg_formatLength:tempData.length];
    }
    // 模板
    else if ([cellData isKindOfClass:FGTemplateMessageCellData.class]) {
        FGTemplateMessageCellData *tempData = (FGTemplateMessageCellData *)cellData;
        model.msgType = FGChatMessageTypeTemplate;
        model.notice = @"[模版消息]";
        model.content = tempData.templateData[@"name"];
        id t = [tempData.templateData valueForKeyPath:@"data.websiteId"];
        NSNumber *websiteId = [t isKindOfClass:NSArray.class] ? ((NSArray *)t).firstObject : t;
        model.websiteId = websiteId; ///< 站点id 1;
        FGTemplateType tempType = [tempData.templateData[@"type"] integerValue];
        model.tempType = tempType; ///< 模板类型
        NSNumber *tempId = tempData.templateData[@"id"];
        model.tempId = tempId; ///< 模板id        
        model.tempJson = [[FGChatKit sharedKit] singleTemplateJsonStr:model.tempType tempId:model.tempId];
        // 处理表单模板
        if (tempType == FGTemplateTypeFrom) {
            model.content = @"已向访客发送信息收集的表单";
        }
    }
    
    return model;
}

@end
